//
//  DINGMicroblogStatus.swift
//  0730Microblog
//
//  Created by ding on 15/8/6.
//  Copyright © 2015年 ding. All rights reserved.
//

import UIKit
import SDWebImage

class DINGMicroblogStatus: NSObject {
    
    typealias DCZFinishedCallBack = (result: [String : AnyObject]?, error: NSError?)->()
 /// 微博创建时间
    var created_at: String?
 /// 微博内容
    var text: String?
 /// 微博来源
    var source: String?
 /// 微博配图数组
    var pic_urls: [[String: String]]?
 /// 图片加载地址
    var pictureURLs: [[String: String]]? {
        return (retweeted_status == nil) ? pic_urls : retweeted_status?.pic_urls
    }
 /// 微博ID（每个微博的唯一标识）
    var id: Int = 0
 /// 微博用户信息
    var user: DINGMicroblogUser?
    
    var retweeted_status: DINGMicroblogStatus?
    
    init(dict: [String : AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
 /// 微博行高
    var rowHeight: CGFloat?
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String : AnyObject] {
                user = DINGMicroblogUser(dict: dict)
            }
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value as? [String : AnyObject] {
                retweeted_status = DINGMicroblogStatus(dict: dict)
//                print(retweeted_status?.pic_urls)
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    //MARK: - 加载微博数据
    class func loadMicroblog(finished: (statusResult: [DINGMicroblogStatus]?, error: NSError?) -> ()) {
        DINGNetTool.sharedNetTool.loadStatus { (result, error) -> () in
            if error != nil || result == nil {
                finished(statusResult: nil, error: error)
                return
            }
            let statusArray = result!["statuses"] as! [[String : AnyObject]]
            var statuses = [DINGMicroblogStatus]()
            for dict in statusArray {
                statuses.append(DINGMicroblogStatus(dict: dict))
            }
            // 可以不用self 因为类只有一个，如果是对象那么必须要用
            cacheWebImage(statuses, finished: finished)
        }
    }
    
    // MARK: - 根据url缓存图片
    private class func cacheWebImage(statuses: [DINGMicroblogStatus], finished: (statusResult: [DINGMicroblogStatus]?, error: NSError?) -> ()) {
        let group = dispatch_group_create()
        for status in statuses {
//            print(status.pictureURLs)
            guard let urls = status.pictureURLs else {
                continue
            }
//            print(urls)
            for imageUrl in urls {
                let url = NSURL(string: imageUrl["thumbnail_pic"]!)
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
                    print(image)
                    dispatch_group_leave(group)
                    
                })
                
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            print("图片下载完成-----")
            finished(statusResult: statuses, error: nil)
        })
    }
    
}
